package com.fivefu.core.util;

import cn.hutool.core.util.StrUtil;
import com.fivefu.core.context.FfSpringContextHolder;
import com.fivefu.core.pojo.FfDataSource;
import com.fivefu.core.config.FFDynamicDS;
import com.zaxxer.hikari.HikariDataSource;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/4
 */
public class DataSourceUtil {

    public static DataSource makeNewDataSource(FfDataSource dbInfo) {
        String url = "jdbc:mysql://" + dbInfo.getUrl() + ":" + dbInfo.getPort() + "/" + dbInfo.getFfSchema()
                + "?useSSL=false&serverTimezone=GMT%2B8&characterEncoding=UTF-8";
        String driveClassName = StrUtil.isEmpty(dbInfo.getDriverName()) ? "com.mysql.cj.jdbc.Driver" : dbInfo.getDriverName();
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setJdbcUrl(url);
        hikariDataSource.setUsername(dbInfo.getUsername());
        hikariDataSource.setPassword(dbInfo.getPassword());
        hikariDataSource.setDriverClassName(driveClassName);
        return  hikariDataSource;
//        return DataSourceBuilder.create().url(url)
//                .driverClassName(driveClassName)
//                .username(dbInfo.getUsername())
//                .password(dbInfo.getPassword())
//                .build();
    }

    /**
     * 添加数据源到动态源中
     *
     * @param dataSource
     */
    public static void addDataSourceToDynamic(FfDataSource dataSource) {
        FFDynamicDS dynamicDataSource = FfSpringContextHolder.getContext().getBean(FFDynamicDS.class);
        List<FfDataSource> list =  new ArrayList(){
            {
                add(dataSource);
            }
        };
        dynamicDataSource.addDataSource(list);
    }


    public static void addDataSourceListToDynamic(List<FfDataSource> dataSource) {
        FFDynamicDS dynamicDataSource = FfSpringContextHolder.getContext().getBean(FFDynamicDS.class);
        dynamicDataSource.addDataSource(dataSource);
    }


}
